import { domToForeignObjectSvg } from "modern-screenshot";

function Print(selector: string) {
  return new Promise(async (resolve, reject) => {
    const dom = document.querySelector(selector);
    if (!dom) return;
    const elements = dom.querySelectorAll("img");
    // 添加水印
    elements.forEach((item) => {
      item.style.pageBreakInside = "avoid";
    });
    const svg = await domToForeignObjectSvg(dom as HTMLElement);
    // 遍历所有的元素，添加打印样式
    const doc = `<html><head><style>
  body{margin:0;padding:0;}
  </style></head><body>${svg.outerHTML}
  </body></html>`;
    // const win = window.open("", "_blank");
    // win?.document.write(doc);
    // 使用iframe打印;
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    document.body.appendChild(iframe);
    iframe.srcdoc = doc;
    iframe.addEventListener("load", () => {
      iframe.contentWindow?.print();
      iframe.contentWindow?.addEventListener("afterprint", () => {
        document.body.removeChild(iframe);
        resolve(true);
      });
    });
  });
}
export default Print;
